from wechatpayv3 import WeChatPay, WeChatPayType
import datetime
MCHID = "1604603809"  # 商户号
APIV3_KEY = "Udns3GE2NHUfzWAJ22FanS5R0yOM66yt"  # 商户秘钥V3 使用V3接口必须使用V3秘钥
CERT_SERIAL_NO = "722F7BD6E6DFB96D4E372CF34FD09758B4DBFB26"  # 证书序列号

# ======================前三个参数在微信支付中可找到===============================
# ============ 商户号(mchid ) 在账户中心——商户信息——微信支付商户号 （是纯数字） ==================
# ============= 商户秘钥(pay_key) 在账户中心——API安全——APIv3秘钥 （需手动设置） ===================
# ============= 证书序列号(serial_num) 在账户中心——API安全——API证书 （需手动申请,通过后会有串证书序列号），申请完成后需要把证书下载到项目中，便于使用 ===================


APPID = "wxf208c5902a55d25b"  # 微信小程序appid
wx_secret = "ad3a871b6198e2a179409002b3b79c10"  # 微信小程序秘钥
# ============= 微信小程序appid 在产品中心——AppID账号管理——添加关联的AppID  ===================

WX_Pay_URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"
# ============= 微信支付调用地址,用于请求接收 预支付交易会话标识: prepay_id ===================


WX_Notify_URL = "https://skbjy.skwhjt.com/api/v1/operation/record/wechat/callback"

PRIVATE_KEY = """-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCpgnGp9HY1SWOd
jHSEMxxVrb03WwD1FjWAMVNpVYAZ6geHW1/pJNHRK7YfBkIEuTWPjmKpc5ZZuY9X
TdKX0/rrc8xmJgC8d5KF2CS3cn5MBqtc63rfTRUqs38ZdX4jDBW556tFHHorje3/
yM6bPx9G7a56YDjU+71sgXz+1ptdSGR0u0AYHpRe0k/VFBMVZntpGDyKiy5NglzK
HPSc3n1co3zcVSZUR5nr8WUuVaJhw74jaAJi39ogaVdBIciBzJ/39uUNLWVO3/Jm
h/dHnL4JhpgKcsdtLarhMrI6PTIupkGG6eBcuqK83fVtq97DmM65Ub2TA6lsYo2J
5njqA0wXAgMBAAECggEAY6YiqdX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t911R
UbYrXIGB6kr5WNfoFbHG6Dmy4BpbsjqBv6fwPhwaxqbTVe18iydkPhPa63RqWSB3
IeYNJj7pqJ2oqBDWeTC5L+zn9Xobx1YfB0rwqfgI9Gqw245pE/RmjBdGocLBtib8
um1B2RYtypywCyqYHkuHqBc=
-----END PRIVATE KEY-----"""
#
# with open('./apiclient_key.pem') as f:
#     PRIVATE_KEY = f.read()

class WxPayV3(object):
    def __init__(self, NOTIFY_URL):
        # 初始化# 接入模式:False=直连商户模式，True=服务商模式
        # PARTNER_MODE = False# 代理设置，None或者{"https": "http://10.10.1.10:1080"}，详细格式参见https://docs.python-requests.org/zh_CN/latest/user/advanced.html
        # PROXY = None
        self.wxpay = WeChatPay(
                                wechatpay_type=WeChatPayType.MINIPROG,
                                mchid=MCHID,
                                private_key=self.get_apiclient_key(),
                                cert_serial_no=CERT_SERIAL_NO,
                                apiv3_key=APIV3_KEY,
                                appid=APPID,
                                notify_url=NOTIFY_URL)

    def get_apiclient_key(self):
        return PRIVATE_KEY

    # def pay_h5(self, payer_client_ip="120.41.220.97", description='demo-description', amount=1,
    #            out_trade_no=str(int(time.time() * 100000))):
    #     # h5支付下单，wxpay初始化的时候，wechatpay_type设置为WeChatPayType.H5。
    #     # 下单成功后，将获取的的h5_url传递给前端跳转唤起支付。 # 标价金额 订单总金额，单位为分
    #     # 商家参数格式有误，请联系商家解决  需要设置请求头referer 商户申请H5时提交的授权域名");//例如 http://www.baidu.com )
    #     code, message = self.wxpay.pay(
    #         description=description,
    #         out_trade_no=out_trade_no,
    #         amount={'total': amount},
    #         scene_info={
    #             "payer_client_ip": payer_client_ip,
    #             "h5_info": {
    #                 "type": "Wap"
    #             }
    #         },
    #     )
    #     return {'code': code, 'message': eval(message)}

    def query(self, out_trade_no):
        """查询订单
        :param transaction_id: 微信支付订单号，示例值：1217752501201407033233368018
        :param out_trade_no: 商户订单号，示例值：1217752501201407033233368018
        :param mchid: 微信支付商户号，可不传，默认传入初始化的mchid。示例值：'987654321'
        :param sub_mchid: (服务商模式)子商户的商户号，由微信支付生成并下发。示例值：'1900000109'"""
        rsp = self.wxpay.query(
            out_trade_no=out_trade_no,
        )
        return rsp

    def random_8(self):
        current_date = datetime.datetime.now().strftime('%Y%m%d')
        return current_date
    def refund2(self,  refund,total,transaction_id, out_trade_no=None, out_refund_no=None ):
        """申请退款
            :param out_refund_no: 商户退款单号，示例值：'1217752501201407033233368018'
            :param amount: 金额信息，示例值：{'refund':888, 'total':888, 'currency':'CNY'}
            :param transaction_id: 微信支付订单号，示例值：'1217752501201407033233368018'
            :param out_trade_no: 商户订单号，示例值：'1217752501201407033233368018'
            :param reason: 退款原因，示例值：'商品已售完'
            :param funds_account: 退款资金来源，示例值：'AVAILABLE'
            :param goods_detail: 退款商品，示例值：{'merchant_goods_id':'1217752501201407033233368018', 'wechatpay_goods_id':'1001', 'goods_name':'iPhone6s 16G', 'unit_price':528800, 'refund_amount':528800, 'refund_quantity':1}
            :param notify_url: 通知地址，示例值：'https://www.weixin.qq.com/wxpay/pay.php'
            :param sub_mchid: (服务商模式)子商户的商户号，由微信支付生成并下发。示例值：'1900000109'
            """
        if not out_refund_no:
            tmp = self.random_8()
            out_refund_no = f"{tmp}{transaction_id[-8:]}"
        rsp = self.wxpay.refund(
            out_trade_no=out_trade_no,
            transaction_id=transaction_id,
            amount={
                'refund': refund,
                'total': total,
                'currency': 'CNY',
            },
            # reason=reason,
            out_refund_no=out_refund_no,
        )
        return rsp

    def close(self, out_trade_no):
        rsp = self.wxpay.close(
            out_trade_no=out_trade_no,
        )
        return rsp
